package way.learning.zz.FtpUtils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.TimeZone;

/**
 * <pre>
 * Created with IntelliJ IDEA.
 * User: zhengzhi
 * Date: 2017/8/9
 * Time: 17:43
 * To change this template use File | Settings | File Templates.
 * </pre>
 *
 * @author Administrator
 */


public class FtpDownloader {
    
    private FTPClient ftpClient;
    private String strIp;
    private int intPort;
    private String user;
    private String password;

    private static final Logger logger = Logger.getLogger("FtpDownloader");

    private static String encoding = System.getProperty("file.encoding");

    /* *
     * Ftp构造函数
     */
    public FtpDownloader(String strIp, int intPort, String user, String Password) {
        this.strIp = strIp;
        this.intPort = intPort;
        this.user = user;
        this.password = Password;
        this.ftpClient = new FTPClient();
    }
    /**
     *判断是否登入成功
     * */
    public boolean ftpLogin() {
        boolean isLogin = false;
        FTPClientConfig ftpClientConfig = new FTPClientConfig();
        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
        ftpClient.setControlEncoding("GBK");
        ftpClient.configure(ftpClientConfig);
        try {
            if (intPort > 0) {
                ftpClient.connect(strIp, intPort);
            }else {
                ftpClient.connect(strIp);
            }
            // FTP服务器连接回答
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                logger.error("登录FTP服务失败！");
                return isLogin;
            }
            ftpClient.login(user, password);
            // 设置传输协议
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            logger.info("恭喜" + user + "成功登陆FTP服务器");
            isLogin = true;
        }catch (Exception e) {
            e.printStackTrace();
            logger.error(user + "登录FTP服务失败！" + e.getMessage());
        }
        ftpClient.setBufferSize(1024 * 2);
        ftpClient.setDataTimeout(30 * 1000);
        return isLogin;
    }

    /**
     * 退出关闭服务器链接
     * */
    public void ftpLogOut() {
        if (null != ftpClient && ftpClient.isConnected()) {
            try {
                // 退出FTP服务器
                boolean reuslt = ftpClient.logout();
                if (reuslt) {
                    logger.info("成功退出服务器");
                }
            }catch (IOException e) {
                e.printStackTrace();
                logger.warn("退出FTP服务器异常！" + e.getMessage());
            }finally {
                try {
                    // 关闭FTP服务器的连接
                    ftpClient.disconnect();
                }catch (IOException e) {
                    e.printStackTrace();
                    logger.warn("关闭FTP服务器的连接异常！");
                }
            }
        }
    }

    /***
     * 上传Ftp文件
     * @param localFile 当地文件
     * @param romotUpLoadePath 上传服务器路径 - 应该以/结束
     * */
    public boolean uploadFile(File localFile, String romotUpLoadePath) {
        BufferedInputStream inStream = null;
        boolean success = false;
        try {
            // 改变工作路径
            ftpClient.changeWorkingDirectory(romotUpLoadePath);
            inStream = new BufferedInputStream(new FileInputStream(localFile));
            logger.info(localFile.getName() + "开始上传.....");
            success = this.ftpClient.storeFile(localFile.getName(), inStream);
            if (success == true) {
                logger.info(localFile.getName() + "上传成功");
                return success;
            }
        }catch (FileNotFoundException e) {
            e.printStackTrace();
            logger.error(localFile + "未找到");
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (inStream != null) {
                try {
                    inStream.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }

    /***
     * 下载文件
     * @param remoteFileName   待下载文件名称
     * @param localDires 下载到当地那个路径下
     * @param remoteDownLoadPath remoteFileName所在的路径
     * */

    public boolean downloadFile(String remoteFileName, String localDires,
                                String remoteDownLoadPath) {
        String strFilePath = localDires + remoteFileName;
        BufferedOutputStream outStream = null;
        boolean success = false;
        try {

            ftpClient.changeWorkingDirectory(remoteDownLoadPath);
            System.out.println("当前工作目录为：" + ftpClient.printWorkingDirectory());

            outStream = new BufferedOutputStream(new FileOutputStream(strFilePath));

            logger.info(remoteFileName + "开始下载....");
            success = ftpClient.retrieveFile(remoteFileName, outStream);
            if (success == true) {
                logger.info(remoteFileName + "成功下载到" + strFilePath);
                return success;
            }
        }catch (Exception e) {
            e.printStackTrace();
            logger.error(remoteFileName + "下载失败");
        }finally {
            if (null != outStream) {
                try {
                    outStream.flush();
                    outStream.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (success == false) {
            logger.error(remoteFileName + "下载失败!!!");
        }
        return success;
    }

    /***
     * @上传文件夹
     * @param localDirectory
     *            当地文件夹
     * @param remoteDirectoryPath
     *            Ftp 服务器路径 以目录"/"结束
     * */
    public boolean uploadDirectory(String localDirectory,
                                   String remoteDirectoryPath) {
        File src = new File(localDirectory);
        try {
            remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
            boolean makeDirFlag = this.ftpClient.makeDirectory(remoteDirectoryPath);
            System.out.println("localDirectory : " + localDirectory);
            System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);
            System.out.println("src.getName() : " + src.getName());
            System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);
            System.out.println("makeDirFlag : " + makeDirFlag);
            // ftpClient.listDirectories();
        }catch (IOException e) {
            e.printStackTrace();
            logger.info(remoteDirectoryPath + "目录创建失败");
        }
        File[] allFile = src.listFiles();
        for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
            if (!allFile[currentFile].isDirectory()) {
                String srcName = allFile[currentFile].getPath().toString();
                uploadFile(new File(srcName), remoteDirectoryPath);
            }
        }
        for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
            if (allFile[currentFile].isDirectory()) {
                // 递归
                uploadDirectory(allFile[currentFile].getPath().toString(),
                        remoteDirectoryPath);
            }
        }
        return true;
    }

    /***
     * @下载文件夹
     * @param localDirectoryPath 本地地址
     * @param remoteDirectory 远程文件夹
     * */
    public boolean downLoadDirectory(String localDirectoryPath, String remoteDirectory) {
        try {
//            String directoryName = new File(remoteDirectory).getPath();

            localDirectoryPath = localDirectoryPath + "/08/08";
            new File(localDirectoryPath).mkdirs();

            /**
             * 获取远程服务器目录下的文件及文件夹
             */
            FTPFile[] allFile = ftpClient.listFiles(remoteDirectory);

            logger.info("文件个数 " + allFile.length);

            for (int i = 0;i < allFile.length;i++) {
                if (allFile[i].isFile()) {
                    downloadFile(allFile[i].getName(),localDirectoryPath, remoteDirectory);
                }else{
                    String remoteDirectoryPath = remoteDirectory + "/"+ allFile[i].getName();
                    downLoadDirectory(localDirectoryPath,remoteDirectoryPath);
                }
            }
        }catch (IOException e) {
            e.printStackTrace();
            logger.info("下载文件夹失败");
            return false;
        }
        return true;
    }


    /**
     * Description: 从FTP服务器下载文件
     *
     * @param url FTP服务器hostname
     * @param port FTP服务器端口
     * @param username FTP登录账号
     * @param password FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName 要下载的文件名
     * @param localPath 下载后保存到本地的路径
     *
     * @return
     */
    public boolean downFile(String url, int port, String username,
                            String password, String remotePath, String fileName,
                            String localPath) {
        boolean result = false;
        try {
            int reply;
            ftpClient.setControlEncoding(encoding);

            /*
             *  为了上传和下载中文文件，有些地方建议使用以下两句代替
             *  new String(remotePath.getBytes(encoding),"iso-8859-1")转码。
             *  经过测试，通不过。
             */
//            FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
//            conf.setServerLanguageCode("zh");

            // 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftpClient.connect(url, port);

            // 登录
            ftpClient.login(username, password);

            // 设置文件传输类型为二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

            // 获取ftp登录应答代码
            reply = ftpClient.getReplyCode();
            // 验证是否登陆成功
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                System.err.println("FTP server refused connection.");
                return result;
            }
            // 转移到FTP服务器目录至指定的目录下
            ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));

            // 获取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());
                    OutputStream is = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }

            ftpClient.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }


    /**
     *
     * 从远程服务器下载文件到本地
     *
     * 没有使用apache的ftpclient,直接使用java的api
     *
     * @param urlString
     * @return
     */
    public static String downloadFileFromRemote(String urlString){
        //此方法兼容HTTP和FTP协议
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ( (line = reader.readLine()) != null) {
                buffer.append(line + "/n");
            }
            reader.close();
        }
        catch (MalformedURLException e) {
            System.out.println("Unable to connect to URL: " + urlString);
        }
        catch (IOException e) {
            System.out.println("IOException when connecting to URL: " + urlString);
        }
        return buffer.toString();
    }




    // FtpClient的Set 和 Get 函数
    public FTPClient getFtpClient() {
        return ftpClient;
    }
    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }


    /**
     * 这一步出现问题 if ((socket = _openDataConnection_(FTPCommand.RETR, remote)) == null) return false;
     *
     * @param args
     * @throws IOException
     */
    
    public static void main(String[] args) throws IOException {

        ///disk/ftp/ndycfd1

        String remoteStr = "/breader/2017/08/08/08/";
        String localStr = "E:/projectRelated/HqData/unicomData2017/2017/test/";

        FtpDownloader ftp = new FtpDownloader("119.23.14.212",21001,"ndycfd1","3GwUS6r");
        ftp.ftpLogin();
//        //上传文件夹
//        boolean uploadFlag = ftp.uploadDirectory("D:\\test02", "/"); //如果是admin/那么传的就是所有文件，如果只是/那么就是传文件夹
//        System.out.println("uploadFlag : " + uploadFlag);


        //下载文件夹
//        ftp.downLoadDirectory(localStr, remoteStr);

        ftp.downloadFile("HQ08S1708080000.051",localStr,remoteStr);
        ftp.ftpLogOut();
    }
}
